<template>
  <div class="model-attr-table-data-container" id="model-attr-table-data-container">
    <common-border-table ref="tableData"
       :table-data="tableData"
       v-loading="loading"
       :table-title="tableTitle"
       :filterable="true"
       :filter-info="filterInfo"
       @search-data="filterData"
       @clear-data="resetData"
       type="selection"
       @selection-change="selectionChange"
       @row-click="rowClick">
      <template #tableToolbar>
        <div class="table-toolbar">
          <div class="fl" v-if="modelInfo && modelInfo.canAddExtAttr">
            <el-button type="primary" icon="el-icon-plus" plain size="small" @click="addAttr">新建</el-button>
            <el-button type="success" icon="el-icon-circle-plus-outline" plain size="small" @click="addBatch">批量添加</el-button>
            <el-button type="danger" icon="el-icon-minus" plain size="small" @click="deleteAttrs('')">删除</el-button>
            <el-button type="success" icon="el-icon-check" plain size="small" @click="publishAttrs()">发布属性</el-button>
          </div>
          <div class="fr" style="margin-right: 10px; width: 120px;">
            <el-select v-model="modelAttrFrom" size="small" @change="changeAttrFrom">
              <el-option label="所有属性" value="all"></el-option>
              <el-option label="自身属性" value="self"></el-option>
              <el-option label="父属性" value="parent"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template #icon="scope">
        <i :class="scope.row.icon" v-if="scope.row.iconType === 'element-ui' && scope.row.icon"></i>
      </template>

      <template #rowOption="scope">
        <el-button @click="deleteAttrs(scope.row)" type="text" size="small" style="color: red;"
                   v-if="modelInfo && modelInfo.canAddExtAttr && !scope.row.published">删除</el-button>
        <el-button type="text" size="small" @click="editAttr(scope.row)">编辑</el-button>
      </template>
    </common-border-table>

    <model-attr-form :visible="showCreateForm" @removed="openAndCloseDialog" v-if="showCreateForm"
                :item-info="editData" :defaultWeight="getMaxWeight" :edit="edit" @updateTable="updateTableData"
                :model-info="modelInfo">
    </model-attr-form>

    <add-batch-attrs :visible="showBatch" @removed="closeAddBatch" v-if="showBatch"
                      @addBatchAttrs="addBatchAttrs"></add-batch-attrs>
  </div>
</template>

<script>

import {getModelAttrs, deleteModelAttrs, publishedAttrs, addBatchAttrs} from '@/js/api/model/modelAttr'
import CommonBorderTable from '@/components/common/CommonBorderTable'
import ModelAttrForm from '@/components/model/ModelAttrForm'
import AddBatchAttrs from '@/components/model/AddBatchAttrs'
import {tableTitle, filterInfo} from '@/js/model/modelAttrTableConfig'
import TableDataMixins from '@/components/mixins/table/TableDataMixins'
import {getModelDefinition} from '@/js/api/model/modelDefinition'

export default {
  name: 'ModelAttributeTableData',
  props: {
    id: {
      type: [String, Number],
      default: ''
    }
  },
  components: {
    ModelAttrForm,
    CommonBorderTable,
    AddBatchAttrs
  },
  mixins: [TableDataMixins],
  data(){
    return {
      edit: false,
      modelInfo: undefined,
      selections: [],
      // self | parent | all
      modelAttrFrom: 'self',
      editData: undefined,
      showBatch: false
    }
  },
  methods: {
    async getModelAttrs(){
      this.loading = true
      const tableData = await getModelAttrs(this.id, this.modelAttrFrom)
      if (tableData.errorMsg){
        this.$msgAlert(tableData.errorMsg, 'error')
      } else {
        this.sourceTableData = tableData.data
        this.tableData = [...this.sourceTableData]
      }
      this.loading = false
    },
    createMenuItem(){
      this.edit = false
      this.openAndCloseDialog(true, false)
    },
    async getModelDefinition(id){
      const modelDefinition = await getModelDefinition(id || this.id)
      if (modelDefinition.errorMsg){
        this.$tips(modelDefinition.errorMsg, 'error')
      } else {
        this.modelInfo = modelDefinition.data
      }
    },
    selectionChange(selections){
      this.selections = selections
    },
    rowClick(row){
      const elTable = this.getElTable()
      elTable.clearSelection()
      elTable.toggleRowSelection(row, true)
    },
    async changeAttrFrom(){
      await this.getModelAttrs()
      this.filterData(this.$refs.tableData.getFilterData())
    },
    addAttr(){
      this.showCreateForm = true
      this.edit = false
      this.editData = undefined
    },
    editAttr(data){
      this.showCreateForm = true
      this.editData = data
      this.edit = true
    },
    deleteAttrs(data){
      let deleteData = []
      if (typeof data === 'object'){
        deleteData.push(data)
      } else {
        deleteData = this.selections
      }
      if (deleteData.length <= 0){
        this.$tips('请选择要删除的数据', 'warning')
        return
      }
      const index = deleteData.findIndex(item => item.published)
      if (index >= 0){
        this.$tips('选择的数据包含已发布的属性，不能删除！', 'warning')
        return
      }
      const loading = this.$appLoading('数据删除中。。。', '#model-attr-table-data-container')
      const idArr = []
      deleteData.forEach(item => idArr.push(item.id))
      this.$myConfirm('是否确定删除？', () => {
        deleteModelAttrs(idArr, this.id).then(resp => {
          if (resp.errorMsg){
            this.$tips(resp.errorMsg, 'error')
          } else {
            idArr.forEach(value => {
              let index1 = this.tableData.findIndex(value1 => value === value1.id)
              if (index1 >= 0){
                this.tableData.splice(index1, 1)
              }
              index1 = this.sourceTableData.findIndex(value1 => value === value1.id)
              if (index1 >= 0){
                this.sourceTableData.splice(index1, 1)
              }
            })
          }
          loading.close()
        }).catch(resp => {
          this.$tips(resp, 'error')
          loading.close()
        })
      }, () => loading.close())
    },
    updateTableData(attr){
      if (!this.edit){
        this.sourceTableData.push(attr)
        this.tableData.push(attr)
      } else {
        const v = this.sourceTableData.find(value => value.id === attr.id)
        if (v){
          const keys = Object.keys(attr)
          keys.forEach(key => { this.$set(v, key, attr[key]) })
        }
      }
      this.filterData(this.$refs.tableData.getFilterData())
    },
    publishAttrs(){
      if (this.selections.length <= 0){
        this.$tips('请选择要发布的属性！', 'error')
        return
      }
      if (this.selections.findIndex(value => value.published === true || value.published === 'true') >= 0){
        this.$tips('请选择未发布的属性进行发布！', 'error')
        return
      }
      this.$myConfirm('发布之后该属性不能被删除，是否确认继续该操作？', () => {
        this._publishAttrs()
      })
    },
    async _publishAttrs(){
      const loading = this.$appLoading('数据删除中。。。', '#model-attr-table-data-container')
      const attrs = []
      this.selections.forEach(value => { attrs.push(value.id) })
      const response = await publishedAttrs(this.modelInfo.id, attrs)
      if (response.errorMsg){
        this.$tips(response.errorMsg, 'error')
      } else {
        const na = this.sourceTableData.filter(value => attrs.findIndex(value1 => value1 === value.id) >= 0)
        na.forEach(value => { value.published = true })
        this.filterData(this.$refs.tableData.getFilterData())
      }
      loading.close()
    },
    addBatch(){
      this.showBatch = true
    },
    closeAddBatch(){
      this.showBatch = false
    },
    async addBatchAttrs(attrs){
      const index = attrs.findIndex(value => {
        return this.sourceTableData.findIndex(value1 => value1.code === value.code) < 0
      })
      if (index < 0) {
        this.$msgAlert('添加的属性编号在该模型下都存在，请重新选择要批量添加的属性！', 'error')
        return
      }

      const response = await addBatchAttrs(attrs, this.id)
      if (response.errorMsg) {
        this.$tips(response.errorMsg, 'error')
        return
      }
      this.$tips('属性批量添加成功。')
      this.$refs.tableData.resetFilter()
      await this.getModelAttrs()
    }
  },
  computed: {
    getMaxWeight(){
      let weight = 0
      this.tableData.forEach(item => {
        if (item.weight && item.weight > weight){
          weight = item.weight
        }
      })
      return weight + 1
    }
  },
  created(){
    this.initData(filterInfo, tableTitle)
    this.getModelAttrs()
    this.getModelDefinition()
  }
}
</script>

<style lang="less">
  .model-attr-table-data-container{
    height: inherit;
  }
</style>
